//! # 中间件模块
//!
//! 基于新的Middleware接口重构的中间件系统，提供统一的请求处理流水线。
//! 包含认证、限流、日志等核心中间件实现。

use axum::{
    extract::{Request as AxumRequest, State},
    http::{HeaderMap, StatusCode},
    middleware::Next,
    response::Response,
};
use async_trait::async_trait;
use std::collections::HashMap;
use std::sync::Arc;
use log;

// 引入新的核心接口
use crate::core::{
    Middleware, GatewayRequest, GatewayResponse, GatewayContext, GatewayResult, GatewayError
};

/// 过滤器状态（保持向后兼容）
#[derive(Debug, Clone)]
pub enum FilterResult {
    Continue,
    Reject(StatusCode, String),
    ModifyRequest(HashMap<String, String>),
}

/// 传统请求过滤器trait（保持向后兼容）
#[async_trait]
pub trait RequestFilter: Send + Sync {
    async fn filter(
        &self,
        method: String,
        uri: String,
        headers: HeaderMap,
    ) -> FilterResult;
}

/// 认证中间件（实现新的Middleware接口）
pub struct AuthMiddleware {
    pub api_keys: HashMap<String, String>,
    pub required: bool,
}

impl AuthMiddleware {
    pub fn new(required: bool) -> Self {
        Self {
            api_keys: HashMap::new(),
            required,
        }
    }

    pub fn add_key(mut self, key: impl Into<String>, service: impl Into<String>) -> Self {
        self.api_keys.insert(key.into(), service.into());
        self
    }
    
    /// 检查API密钥是否有效
    fn validate_api_key(&self, headers: &HeaderMap) -> bool {
        if !self.required {
            return true;
        }
        
        if let Some(api_key) = headers.get("X-API-Key").and_then(|v| v.to_str().ok()) {
            return self.api_keys.contains_key(api_key);
        }
        
        false
    }
}

#[async_trait]
impl Middleware for AuthMiddleware {
    async fn before_request(&self, mut request: GatewayRequest, context: Arc<GatewayContext>) -> GatewayResult<GatewayRequest> {
        if !self.validate_api_key(&request.headers) {
            return Err(GatewayError::authentication("无效或缺少API密钥"));
        }
        
        // 如果认证成功，可以在这里添加认证信息到上下文
        // 更新context中的认证信息将在完整的认证系统中实现
        
        Ok(request)
    }
    
    async fn after_response(&self, response: GatewayResponse, _context: Arc<GatewayContext>) -> GatewayResult<GatewayResponse> {
        // 认证中间件不需要处理响应
        Ok(response)
    }
    
    fn name(&self) -> &str {
        "AuthMiddleware"
    }
    
    fn priority(&self) -> i32 {
        10 // 认证中间件应该有较高的优先级
    }
}

/// 认证过滤器（保持向后兼容）
pub struct AuthFilter {
    pub api_keys: HashMap<String, String>,
    pub required: bool,
}

impl AuthFilter {
    pub fn new(required: bool) -> Self {
        Self {
            api_keys: HashMap::new(),
            required,
        }
    }

    pub fn add_key(mut self, key: impl Into<String>, service: impl Into<String>) -> Self {
        self.api_keys.insert(key.into(), service.into());
        self
    }
}

#[async_trait]
impl RequestFilter for AuthFilter {
    async fn filter(
        &self,
        _method: String,
        _uri: String,
        headers: HeaderMap,
    ) -> FilterResult {
        if !self.required {
            return FilterResult::Continue;
        }

        if let Some(api_key) = headers.get("X-API-Key").and_then(|v| v.to_str().ok()) {
            if self.api_keys.contains_key(api_key) {
                return FilterResult::Continue;
            }
        }

        FilterResult::Reject(
            StatusCode::UNAUTHORIZED,
            "Invalid or missing API key".to_string(),
        )
    }
}

/// 限流中间件（实现新的Middleware接口）
pub struct RateLimitMiddleware {
    pub max_requests: u32,
    pub window_duration: std::time::Duration,
    pub requests: Arc<tokio::sync::RwLock<HashMap<String, Vec<std::time::Instant>>>>,
}

impl RateLimitMiddleware {
    pub fn new(max_requests: u32, window_duration: std::time::Duration) -> Self {
        Self {
            max_requests,
            window_duration,
            requests: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
        }
    }

    async fn get_client_key(&self, headers: &HeaderMap) -> String {
        // 优先使用X-Forwarded-For，然后使用X-Real-IP，最后使用连接IP
        headers
            .get("X-Forwarded-For")
            .and_then(|v| v.to_str().ok())
            .or_else(|| headers.get("X-Real-IP").and_then(|v| v.to_str().ok()))
            .unwrap_or("unknown")
            .to_string()
    }

    async fn is_allowed(&self, client_key: &str) -> bool {
        let mut requests = self.requests.write().await;
        let now = std::time::Instant::now();
        
        let client_requests = requests
            .entry(client_key.to_string())
            .or_insert_with(Vec::new);

        // 清理过期的请求记录
        client_requests.retain(|timestamp| now.duration_since(*timestamp) < self.window_duration);

        if client_requests.len() < self.max_requests as usize {
            client_requests.push(now);
            true
        } else {
            false
        }
    }
}

#[async_trait]
impl Middleware for RateLimitMiddleware {
    async fn before_request(&self, request: GatewayRequest, context: Arc<GatewayContext>) -> GatewayResult<GatewayRequest> {
        let client_key = self.get_client_key(&request.headers).await;
        
        if !self.is_allowed(&client_key).await {
            return Err(GatewayError::rate_limit("超出限流限制"));
        }
        
        Ok(request)
    }
    
    async fn after_response(&self, response: GatewayResponse, _context: Arc<GatewayContext>) -> GatewayResult<GatewayResponse> {
        // 限流中间件不需要处理响应
        Ok(response)
    }
    
    fn name(&self) -> &str {
        "RateLimitMiddleware"
    }
    
    fn priority(&self) -> i32 {
        20 // 限流在认证之后
    }
}

/// 日志中间件（实现新的Middleware接口）
pub struct LoggingMiddleware {
    pub log_level: log::Level,
}

impl LoggingMiddleware {
    pub fn new(log_level: log::Level) -> Self {
        Self { log_level }
    }
}

#[async_trait]
impl Middleware for LoggingMiddleware {
    async fn before_request(&self, request: GatewayRequest, context: Arc<GatewayContext>) -> GatewayResult<GatewayRequest> {
        let header_keys = request.headers.keys().map(|k| k.to_string()).collect::<Vec<_>>();
        
        log::log!(
            self.log_level,
            "[{}] 请求开始: {} {} - 请求头: {:?}",
            request.id,
            request.method,
            request.uri,
            header_keys
        );
        
        Ok(request)
    }
    
    async fn after_response(&self, response: GatewayResponse, context: Arc<GatewayContext>) -> GatewayResult<GatewayResponse> {
        log::log!(
            self.log_level,
            "[{}] 请求完成: 状态={}, 处理时间={}ms",
            context.request_id,
            response.status,
            response.processing_time
        );
        
        Ok(response)
    }
    
    fn name(&self) -> &str {
        "LoggingMiddleware"
    }
    
    fn priority(&self) -> i32 {
        1000 // 日志中间件应该有较低的优先级，在最后执行
    }
}

/// 限流过滤器
pub struct RateLimitFilter {
    pub max_requests: u32,
    pub window_duration: std::time::Duration,
    pub requests: Arc<tokio::sync::RwLock<HashMap<String, Vec<std::time::Instant>>>>,
}

impl RateLimitFilter {
    pub fn new(max_requests: u32, window_duration: std::time::Duration) -> Self {
        Self {
            max_requests,
            window_duration,
            requests: Arc::new(tokio::sync::RwLock::new(HashMap::new())),
        }
    }

    async fn get_client_key(&self,
        headers: &HeaderMap,
    ) -> String {
        // 优先使用X-Forwarded-For，然后使用X-Real-IP，最后使用连接IP
        headers
            .get("X-Forwarded-For")
            .and_then(|v| v.to_str().ok())
            .or_else(|| headers.get("X-Real-IP").and_then(|v| v.to_str().ok()))
            .unwrap_or("unknown")
            .to_string()
    }

    async fn is_allowed(&self,
        client_key: &str,
    ) -> bool {
        let mut requests = self.requests.write().await;
        let now = std::time::Instant::now();
        
        let client_requests = requests
            .entry(client_key.to_string())
            .or_insert_with(Vec::new);

        // 清理过期的请求记录
        client_requests.retain(|timestamp| now.duration_since(*timestamp) < self.window_duration);

        if client_requests.len() < self.max_requests as usize {
            client_requests.push(now);
            true
        } else {
            false
        }
    }
}

#[async_trait::async_trait]
impl RequestFilter for RateLimitFilter {
    async fn filter(
        &self,
        _method: String,
        _uri: String,
        headers: HeaderMap,
    ) -> FilterResult {
        let client_key = self.get_client_key(&headers).await;
        
        if self.is_allowed(&client_key).await {
            FilterResult::Continue
        } else {
            FilterResult::Reject(
                StatusCode::TOO_MANY_REQUESTS,
                "Rate limit exceeded".to_string(),
            )
        }
    }
}

/// 日志过滤器
pub struct LoggingFilter {
    pub log_level: log::Level,
}

impl LoggingFilter {
    pub fn new(log_level: log::Level) -> Self {
        Self { log_level }
    }
}

#[async_trait::async_trait]
impl RequestFilter for LoggingFilter {
    async fn filter(
        &self,
        method: String,
        uri: String,
        headers: HeaderMap,
    ) -> FilterResult {
        let header_keys = headers.keys().map(|k| k.to_string()).collect::<Vec<_>>();

        // Capture owned strings instead of the request reference
        let log_level = self.log_level;
        log::log!(
            log_level,
            "Request: {} {} - Headers: {:?}",
            method,
            uri,
            header_keys
        );
        FilterResult::Continue
    }
}

/// 过滤器链
pub struct FilterChain {
    filters: Vec<Box<dyn RequestFilter>>,
}

impl FilterChain {
    pub fn new() -> Self {
        Self {
            filters: Vec::new(),
        }
    }

    pub fn add_filter(mut self, filter: Box<dyn RequestFilter>) -> Self {
        self.filters.push(filter);
        self
    }

    pub async fn execute(
        &self,
        request: &AxumRequest,
    ) -> FilterResult {
        let method = request.method().to_string();
        let uri = request.uri().to_string();
        let headers_cloned = request.headers().clone();

        for filter in &self.filters {
            match filter.filter(method.clone(), uri.clone(), headers_cloned.clone()).await {
                FilterResult::Continue => continue,
                result => return result,
            }
        }
        FilterResult::Continue
    }
}

impl Default for FilterChain {
    fn default() -> Self {
        Self::new()
    }
}

/// 新的中间件管道系统
pub struct MiddlewarePipeline {
    middlewares: Vec<Box<dyn Middleware>>,
}

impl MiddlewarePipeline {
    pub fn new() -> Self {
        Self {
            middlewares: Vec::new(),
        }
    }
    
    /// 添加中间件并按优先级排序
    pub fn add_middleware(mut self, middleware: Box<dyn Middleware>) -> Self {
        self.middlewares.push(middleware);
        // 按优先级排序（数值越小优先级越高）
        self.middlewares.sort_by_key(|m| m.priority());
        self
    }
    
    /// 执行所有中间件的前置处理
    pub async fn execute_before_request(
        &self,
        mut request: GatewayRequest,
        context: Arc<GatewayContext>
    ) -> GatewayResult<GatewayRequest> {
        for middleware in &self.middlewares {
            request = middleware.before_request(request, context.clone()).await?;
        }
        Ok(request)
    }
    
    /// 执行所有中间件的后置处理（反向顺序）
    pub async fn execute_after_response(
        &self,
        mut response: GatewayResponse,
        context: Arc<GatewayContext>
    ) -> GatewayResult<GatewayResponse> {
        // 后置处理按相反顺序执行
        for middleware in self.middlewares.iter().rev() {
            response = middleware.after_response(response, context.clone()).await?;
        }
        Ok(response)
    }
    
    /// 获取所有中间件名称
    pub fn get_middleware_names(&self) -> Vec<&str> {
        self.middlewares.iter().map(|m| m.name()).collect()
    }
}

impl Default for MiddlewarePipeline {
    fn default() -> Self {
        Self::new()
    }
}

/// 中间件适配器，将旧的RequestFilter适配到新的Middleware接口
pub struct FilterAdapter {
    filter: Box<dyn RequestFilter>,
    name: String,
    priority: i32,
}

impl FilterAdapter {
    pub fn new(filter: Box<dyn RequestFilter>, name: String, priority: i32) -> Self {
        Self { filter, name, priority }
    }
}

#[async_trait]
impl Middleware for FilterAdapter {
    async fn before_request(&self, request: GatewayRequest, _context: Arc<GatewayContext>) -> GatewayResult<GatewayRequest> {
        let result = self.filter.filter(
            request.method.to_string(),
            request.uri.to_string(),
            request.headers.clone()
        ).await;
        
        match result {
            FilterResult::Continue => Ok(request),
            FilterResult::Reject(status, message) => {
                match status {
                    StatusCode::UNAUTHORIZED => Err(GatewayError::authentication(message)),
                    StatusCode::TOO_MANY_REQUESTS => Err(GatewayError::rate_limit(message)),
                    _ => Err(GatewayError::validation(message))
                }
            },
            FilterResult::ModifyRequest(_) => {
                // TODO: 实现请求修改逻辑
                Ok(request)
            }
        }
    }
    
    async fn after_response(&self, response: GatewayResponse, _context: Arc<GatewayContext>) -> GatewayResult<GatewayResponse> {
        Ok(response)
    }
    
    fn name(&self) -> &str {
        &self.name
    }
    
    fn priority(&self) -> i32 {
        self.priority
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::http::{Method, Uri, HeaderValue};
    use std::time::Duration;
    use crate::core::{GatewayRequest, GatewayResponse, GatewayContext};

    // =============================================================================
    // 辅助函数
    // =============================================================================

    fn create_test_request() -> GatewayRequest {
        let uri = "http://localhost:8080/api/test".parse::<Uri>().unwrap();
        GatewayRequest::new(Method::GET, uri)
    }

    fn create_test_response() -> GatewayResponse {
        GatewayResponse::new(StatusCode::OK)
    }

    fn create_test_context() -> Arc<GatewayContext> {
        Arc::new(GatewayContext::new("test-request-123".to_string()))
    }

    // =============================================================================
    // AuthMiddleware 测试
    // =============================================================================

    #[tokio::test]
    async fn test_auth_middleware_not_required() {
        let middleware = AuthMiddleware::new(false);
        let request = create_test_request();
        let context = create_test_context();

        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_auth_middleware_valid_api_key() {
        let middleware = AuthMiddleware::new(true)
            .add_key("valid-key", "test-service");
        
        let mut request = create_test_request();
        request.headers.insert("X-API-Key", HeaderValue::from_static("valid-key"));
        let context = create_test_context();

        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_auth_middleware_invalid_api_key() {
        let middleware = AuthMiddleware::new(true)
            .add_key("valid-key", "test-service");
        
        let mut request = create_test_request();
        request.headers.insert("X-API-Key", HeaderValue::from_static("invalid-key"));
        let context = create_test_context();

        let result = middleware.before_request(request, context).await;
        assert!(result.is_err());
        
        if let Err(GatewayError::Authentication { message, .. }) = result {
            assert!(message.contains("无效或缺少API密钥"));
        } else {
            panic!("Expected Authentication error");
        }
    }

    #[tokio::test]
    async fn test_auth_middleware_missing_api_key() {
        let middleware = AuthMiddleware::new(true)
            .add_key("valid-key", "test-service");
        
        let request = create_test_request(); // 没有API密钥
        let context = create_test_context();

        let result = middleware.before_request(request, context).await;
        assert!(result.is_err());
        
        match result.unwrap_err() {
            GatewayError::Authentication { message, .. } => {
                assert!(message.contains("无效或缺少API密钥"));
            },
            _ => panic!("Expected Authentication error"),
        }
    }

    #[tokio::test]
    async fn test_auth_middleware_after_response() {
        let middleware = AuthMiddleware::new(true);
        let response = create_test_response();
        let context = create_test_context();

        let result = middleware.after_response(response, context).await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_auth_middleware_name() {
        let middleware = AuthMiddleware::new(true);
        assert_eq!(middleware.name(), "AuthMiddleware");
    }

    #[test]
    fn test_auth_middleware_priority() {
        let middleware = AuthMiddleware::new(true);
        assert_eq!(middleware.priority(), 10);
    }

    #[test]
    fn test_auth_middleware_add_multiple_keys() {
        let middleware = AuthMiddleware::new(true)
            .add_key("key1", "service1")
            .add_key("key2", "service2");
        
        assert_eq!(middleware.api_keys.len(), 2);
        assert_eq!(middleware.api_keys.get("key1"), Some(&"service1".to_string()));
        assert_eq!(middleware.api_keys.get("key2"), Some(&"service2".to_string()));
    }

    // =============================================================================
    // RateLimitMiddleware 测试
    // =============================================================================

    #[tokio::test]
    async fn test_rate_limit_middleware_allowed() {
        let middleware = RateLimitMiddleware::new(10, Duration::from_secs(60));
        let request = create_test_request();
        let context = create_test_context();

        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_rate_limit_middleware_exceeded() {
        let middleware = RateLimitMiddleware::new(2, Duration::from_secs(60));
        let context = create_test_context();

        // 添加相同客户端的请求头
        let mut request1 = create_test_request();
        request1.headers.insert("X-Real-IP", HeaderValue::from_static("192.168.1.100"));
        
        let mut request2 = create_test_request();
        request2.headers.insert("X-Real-IP", HeaderValue::from_static("192.168.1.100"));
        
        let mut request3 = create_test_request();
        request3.headers.insert("X-Real-IP", HeaderValue::from_static("192.168.1.100"));

        // 前两个请求应该成功
        assert!(middleware.before_request(request1, context.clone()).await.is_ok());
        assert!(middleware.before_request(request2, context.clone()).await.is_ok());
        
        // 第三个请求应该被限流
        let result = middleware.before_request(request3, context).await;
        assert!(result.is_err());
        
        match result.unwrap_err() {
            GatewayError::RateLimit { message, .. } => {
                assert!(message.contains("超出限流限制"));
            },
            _ => panic!("Expected RateLimit error"),
        }
    }

    #[tokio::test]
    async fn test_rate_limit_middleware_different_clients() {
        let middleware = RateLimitMiddleware::new(1, Duration::from_secs(60));
        let context = create_test_context();

        let mut request1 = create_test_request();
        request1.headers.insert("X-Real-IP", HeaderValue::from_static("192.168.1.100"));
        
        let mut request2 = create_test_request();
        request2.headers.insert("X-Real-IP", HeaderValue::from_static("192.168.1.101"));

        // 不同客户端的请求应该都被允许
        assert!(middleware.before_request(request1, context.clone()).await.is_ok());
        assert!(middleware.before_request(request2, context).await.is_ok());
    }

    #[tokio::test]
    async fn test_rate_limit_middleware_get_client_key() {
        let middleware = RateLimitMiddleware::new(10, Duration::from_secs(60));
        
        // 测试X-Forwarded-For优先级
        let mut headers = HeaderMap::new();
        headers.insert("X-Forwarded-For", HeaderValue::from_static("192.168.1.100"));
        headers.insert("X-Real-IP", HeaderValue::from_static("192.168.1.101"));
        
        let key = middleware.get_client_key(&headers).await;
        assert_eq!(key, "192.168.1.100");
        
        // 测试X-Real-IP优先级
        let mut headers = HeaderMap::new();
        headers.insert("X-Real-IP", HeaderValue::from_static("192.168.1.101"));
        
        let key = middleware.get_client_key(&headers).await;
        assert_eq!(key, "192.168.1.101");
        
        // 测试默认值
        let headers = HeaderMap::new();
        let key = middleware.get_client_key(&headers).await;
        assert_eq!(key, "unknown");
    }

    #[tokio::test]
    async fn test_rate_limit_middleware_after_response() {
        let middleware = RateLimitMiddleware::new(10, Duration::from_secs(60));
        let response = create_test_response();
        let context = create_test_context();

        let result = middleware.after_response(response, context).await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_rate_limit_middleware_name() {
        let middleware = RateLimitMiddleware::new(10, Duration::from_secs(60));
        assert_eq!(middleware.name(), "RateLimitMiddleware");
    }

    #[test]
    fn test_rate_limit_middleware_priority() {
        let middleware = RateLimitMiddleware::new(10, Duration::from_secs(60));
        assert_eq!(middleware.priority(), 20);
    }

    // =============================================================================
    // LoggingMiddleware 测试
    // =============================================================================

    #[tokio::test]
    async fn test_logging_middleware_before_request() {
        let middleware = LoggingMiddleware::new(log::Level::Info);
        let request = create_test_request();
        let context = create_test_context();

        let result = middleware.before_request(request, context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_logging_middleware_after_response() {
        let middleware = LoggingMiddleware::new(log::Level::Info);
        let response = create_test_response();
        let context = create_test_context();

        let result = middleware.after_response(response, context).await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_logging_middleware_name() {
        let middleware = LoggingMiddleware::new(log::Level::Info);
        assert_eq!(middleware.name(), "LoggingMiddleware");
    }

    #[test]
    fn test_logging_middleware_priority() {
        let middleware = LoggingMiddleware::new(log::Level::Info);
        assert_eq!(middleware.priority(), 1000);
    }

    #[test]
    fn test_logging_middleware_different_levels() {
        let info_middleware = LoggingMiddleware::new(log::Level::Info);
        let debug_middleware = LoggingMiddleware::new(log::Level::Debug);
        let error_middleware = LoggingMiddleware::new(log::Level::Error);
        
        assert_eq!(info_middleware.log_level, log::Level::Info);
        assert_eq!(debug_middleware.log_level, log::Level::Debug);
        assert_eq!(error_middleware.log_level, log::Level::Error);
    }

    // =============================================================================
    // MiddlewarePipeline 测试
    // =============================================================================

    #[tokio::test]
    async fn test_middleware_pipeline_empty() {
        let pipeline = MiddlewarePipeline::new();
        let request = create_test_request();
        let response = create_test_response();
        let context = create_test_context();

        let result = pipeline.execute_before_request(request, context.clone()).await;
        assert!(result.is_ok());
        
        let result = pipeline.execute_after_response(response, context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_middleware_pipeline_single_middleware() {
        let pipeline = MiddlewarePipeline::new()
            .add_middleware(Box::new(LoggingMiddleware::new(log::Level::Info)));
        
        let request = create_test_request();
        let response = create_test_response();
        let context = create_test_context();

        let result = pipeline.execute_before_request(request, context.clone()).await;
        assert!(result.is_ok());
        
        let result = pipeline.execute_after_response(response, context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_middleware_pipeline_multiple_middlewares() {
        let pipeline = MiddlewarePipeline::new()
            .add_middleware(Box::new(AuthMiddleware::new(false)))
            .add_middleware(Box::new(RateLimitMiddleware::new(100, Duration::from_secs(60))))
            .add_middleware(Box::new(LoggingMiddleware::new(log::Level::Info)));
        
        let request = create_test_request();
        let response = create_test_response();
        let context = create_test_context();

        let result = pipeline.execute_before_request(request, context.clone()).await;
        assert!(result.is_ok());
        
        let result = pipeline.execute_after_response(response, context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_middleware_pipeline_priority_order() {
        let pipeline = MiddlewarePipeline::new()
            .add_middleware(Box::new(LoggingMiddleware::new(log::Level::Info))) // priority 1000
            .add_middleware(Box::new(AuthMiddleware::new(false))) // priority 10
            .add_middleware(Box::new(RateLimitMiddleware::new(100, Duration::from_secs(60)))); // priority 20
        
        let names = pipeline.get_middleware_names();
        assert_eq!(names, vec!["AuthMiddleware", "RateLimitMiddleware", "LoggingMiddleware"]);
    }

    #[tokio::test]
    async fn test_middleware_pipeline_auth_failure() {
        let pipeline = MiddlewarePipeline::new()
            .add_middleware(Box::new(AuthMiddleware::new(true))); // 要求认证但没有密钥
        
        let request = create_test_request();
        let context = create_test_context();

        let result = pipeline.execute_before_request(request, context).await;
        assert!(result.is_err());
        
        match result.unwrap_err() {
            GatewayError::Authentication { .. } => {}, // 预期的认证错误
            _ => panic!("Expected Authentication error"),
        }
    }

    #[test]
    fn test_middleware_pipeline_get_middleware_names() {
        let pipeline = MiddlewarePipeline::new()
            .add_middleware(Box::new(AuthMiddleware::new(false)))
            .add_middleware(Box::new(LoggingMiddleware::new(log::Level::Info)));
        
        let names = pipeline.get_middleware_names();
        assert_eq!(names.len(), 2);
        assert!(names.contains(&"AuthMiddleware"));
        assert!(names.contains(&"LoggingMiddleware"));
    }

    // =============================================================================
    // FilterAdapter 测试
    // =============================================================================

    #[tokio::test]
    async fn test_filter_adapter_continue() {
        let auth_filter = AuthFilter::new(false);
        let adapter = FilterAdapter::new(
            Box::new(auth_filter),
            "AuthAdapter".to_string(),
            50
        );
        
        let request = create_test_request();
        let context = create_test_context();

        let result = adapter.before_request(request, context).await;
        assert!(result.is_ok());
    }

    #[tokio::test]
    async fn test_filter_adapter_reject_auth() {
        let auth_filter = AuthFilter::new(true); // 要求认证但没有密钥
        let adapter = FilterAdapter::new(
            Box::new(auth_filter),
            "AuthAdapter".to_string(),
            50
        );
        
        let request = create_test_request();
        let context = create_test_context();

        let result = adapter.before_request(request, context).await;
        assert!(result.is_err());
        
        match result.unwrap_err() {
            GatewayError::Authentication { .. } => {}, // 预期的认证错误
            _ => panic!("Expected Authentication error"),
        }
    }

    #[tokio::test]
    async fn test_filter_adapter_after_response() {
        let auth_filter = AuthFilter::new(false);
        let adapter = FilterAdapter::new(
            Box::new(auth_filter),
            "AuthAdapter".to_string(),
            50
        );
        
        let response = create_test_response();
        let context = create_test_context();

        let result = adapter.after_response(response, context).await;
        assert!(result.is_ok());
    }

    #[test]
    fn test_filter_adapter_name() {
        let auth_filter = AuthFilter::new(false);
        let adapter = FilterAdapter::new(
            Box::new(auth_filter),
            "CustomAdapter".to_string(),
            50
        );
        
        assert_eq!(adapter.name(), "CustomAdapter");
    }

    #[test]
    fn test_filter_adapter_priority() {
        let auth_filter = AuthFilter::new(false);
        let adapter = FilterAdapter::new(
            Box::new(auth_filter),
            "AuthAdapter".to_string(),
            75
        );
        
        assert_eq!(adapter.priority(), 75);
    }

    // =============================================================================
    // 传统 Filter 测试（保持向后兼容）
    // =============================================================================

    #[tokio::test]
    async fn test_filter_chain() {
        let chain = FilterChain::new()
            .add_filter(Box::new(AuthFilter::new(false)))
            .add_filter(Box::new(LoggingFilter::new(log::Level::Info)));

        let request = axum::extract::Request::builder()
            .method(Method::GET)
            .uri("http://localhost/test")
            .body(axum::body::Body::empty()).unwrap();

        let result = chain.execute(&request).await;
        assert!(matches!(result, FilterResult::Continue));
    }

    #[tokio::test]
    async fn test_filter_chain_auth_failure() {
        let chain = FilterChain::new()
            .add_filter(Box::new(AuthFilter::new(true))); // 要求认证

        let request = axum::extract::Request::builder()
            .method(Method::GET)
            .uri("http://localhost/test")
            .body(axum::body::Body::empty()).unwrap();

        let result = chain.execute(&request).await;
        assert!(matches!(result, FilterResult::Reject(StatusCode::UNAUTHORIZED, _)));
    }

    #[tokio::test]
    async fn test_rate_limit_filter() {
        let filter = RateLimitFilter::new(1, Duration::from_secs(60));
        let mut headers = HeaderMap::new();
        headers.insert("X-Real-IP", HeaderValue::from_static("192.168.1.100"));

        // 第一个请求应该成功
        let result = filter.filter("GET".to_string(), "/test".to_string(), headers.clone()).await;
        assert!(matches!(result, FilterResult::Continue));

        // 第二个请求应该被限流
        let result = filter.filter("GET".to_string(), "/test".to_string(), headers).await;
        assert!(matches!(result, FilterResult::Reject(StatusCode::TOO_MANY_REQUESTS, _)));
    }

    #[tokio::test]
    async fn test_logging_filter() {
        let filter = LoggingFilter::new(log::Level::Info);
        let headers = HeaderMap::new();

        let result = filter.filter("GET".to_string(), "/test".to_string(), headers).await;
        assert!(matches!(result, FilterResult::Continue));
    }

    #[test]
    fn test_filter_result_variants() {
        // 测试不同类型的FilterResult
        let continue_result = FilterResult::Continue;
        let reject_result = FilterResult::Reject(StatusCode::BAD_REQUEST, "Bad request".to_string());
        let modify_result = FilterResult::ModifyRequest({
            let mut map = HashMap::new();
            map.insert("X-Modified".to_string(), "true".to_string());
            map
        });

        assert!(matches!(continue_result, FilterResult::Continue));
        assert!(matches!(reject_result, FilterResult::Reject(StatusCode::BAD_REQUEST, _)));
        assert!(matches!(modify_result, FilterResult::ModifyRequest(_)));
    }
}